import CONFIG from './config.js'
const needLoginApi = CONFIG.needLoginApi
let isToLogin = false;

const API = {};
API.getJson = (route, params, method) => {
	let url = CONFIG.host + route;
	let localStorage = uni.getStorageSync('localStorage');

	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			data: params,
			dataType: "json",
			method: method ? method : 'GET',
			success(res) {
				if (res.statusCode != 200) {
					uni.showToast({
						title: '网络错误',
						duration: 2000,
						icon: 'none'
					});
					return;
				}
				

				resolve(res.data)
			},
			fail(res) {
				console.log(`request调用失败`, res);
			}
		});
	});
}
API.getUpload = (route, files, params) => {
	let url = CONFIG.host + route;
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: url,
			filePath: files,
			formData: params,
			name: 'file',
			success: (res) => {
				if (res.statusCode != 200) {
					uni.showToast({
						title: '网络错误',
						duration: 2000
					});
					return false;
				}
				resolve(JSON.parse(res.data))
			}
		});
	});
}
//获取微信支付参数
API.getPayParams = (params) => {

	uni.showLoading({
		title: '加载中',
		mask: true
	});
	let url = CONFIG.host + CONFIG.url['orders_wxPay'];
	let user_info = uni.getStorageSync('user_info')

	params.com_id = 888;
	params.user_id = user_info.user_id
	params.token = user_info.token
	return new Promise((resolve, reject) => {
		uni.request({
			url: url,
			data: params,
			dataType: "json",
			method: "GET",
			success(res) {
				uni.hideLoading();
				if (res.statusCode != 200) {
					uni.showToast({
						title: '网络错误',
						duration: 2000
					});
					return false;
				}
				resolve(res.data)
			},
			fail(res) {
				uni.hideLoading();
				console.log(`request调用失败`);
			}
		});
	});
}
//微信支付
API.wx_pay = function(data) {
	return new Promise((resolve, reject) => {
		uni.requestPayment({
			provider: 'wxpay',
			timeStamp: String(data.timeStamp),
			nonceStr: data.nonceStr,
			package: data.package,
			signType: data.signType,
			paySign: data.paySign,
			success: function(res) {
				resolve(res);
				console.log('success:' + JSON.stringify(res));
			},
			cancel: function(res) {
				uni.showToast({
					title: '已取消支付',
					icon: 'none'
				})
				reject(res);
			},
			fail: function(err) {
				reject(err);
				console.log('fail:' + JSON.stringify(err));
			}
		});

	})
}

export default API;